package com.adcc.swingui.factory;

import java.awt.Container;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComponent;

import org.apache.log4j.Logger;

import com.adcc.swingui.base.DefaultToolBar;
import com.adcc.swingui.bean.ToolBean;
import com.adcc.swingui.bean.ToolComponentBean;
import com.adcc.swingui.conf.ToolBarConf;
import com.jidesoft.action.CommandBar;
import com.jidesoft.action.DefaultDockableBarDockableHolder;
import com.jidesoft.action.DockableBarContext;

public class ToolBarFactory {
	private static Logger logger = Logger.getLogger(ToolBarFactory.class);
	private static Map<String, CommandBar> map = new HashMap<String, CommandBar>();
	
	public static void create(String[] name, Container container) {
		for (int i = 0; i < name.length; i++) {
			if(map.containsKey(name[i])) {
				logger.warn("工具栏对象已经存在" + name[i]);
			}
			ToolBean bean = ToolBarConf.getToolConf().get(name[i]);
			CommandBar commandBar = new CommandBar(name[i]);
			commandBar.setInitSide(DockableBarContext.DOCK_SIDE_NORTH);
			commandBar.setInitMode(DockableBarContext.STATE_HORI_DOCKED);
			if(bean != null){
				commandBar.setInitIndex(bean.getInitIndex());
				for(ToolComponentBean component : bean.getToolList()){
					if(component.getName() == null) {
						commandBar.addSeparator();
					} else {
						try{
							Class c = Class.forName(component.getClassName());
							Constructor con = c.getConstructor(new Class[] { Container.class });
							DefaultToolBar o = (DefaultToolBar) con.newInstance(container);
							JComponent jcomp =o.buildButton(o.getClass().getName());
							jcomp.setEnabled(component.getCompEnabled());
							commandBar.add(jcomp);
						}catch(Exception e){
							logger.error("工具创建失败" + component.getClassName() + e.getMessage());
						}
					}
				}
			}else{
				logger.error("工具栏配置不存在" + name[i]);
			}
			
			//菜单缓存到内存
			map.put(name[i], commandBar);
			//设置到主容器中
			((DefaultDockableBarDockableHolder)container).getDockableBarManager().addDockableBar(commandBar);
		}
	}
}
